import React, {useState, useEffect, useRef} from 'react';
import {Divider, Input, message, Switch } from 'antd';
import {PageContainer} from '@ant-design/pro-layout';
import styles from './style.less';
import {Select, Button, DatePicker} from 'antd';
import {storeList, getPreStore, exportPreCount, getAllStore,changePre,getChangePrePage} from './service';
import moment from 'moment';
import {saveFileAs} from '@/utils/utils';
import CreateForm from '@/pages/Home/component/CreateForm';
import ProTable from '@ant-design/pro-table';
import OrderCommon from "@/pages/OrderCommon";
import {getPayOrder} from "@/pages/OrderManagement/StoreOrder/service";
import Access from '@/components/Access/Access';
const StoreRecharge = () => {
  const actionRef = useRef();
  const [order, setOrder] = useState(false);
  const [payOrderValues, setPayOrderValues] = useState({});
  const [details, setDetails] = useState();
  const [count, setCount] = useState();
  const [detailCount, setDetailCount] = useState();
  const [store, setStore] = useState([]);
  const [storeName, setStoreName] = useState();
  const [storeId, setStoreId] = useState();
  const [timer, setTimer] = useState();
  const [outModal, handleOutModal] = useState(false);
  const [timerObj, setTimerObj] = useState();
  const [preChangeVisible, handlePreChangeVisibleVisible] = useState(false);
  const [preDetailVisible, handlePreDetailVisible] = useState(false);
  const [changeMoneyFlag, setChangeMoneyFlag] = useState(false);
  const [changePreObj, setChangePreObj] = useState({});

  const handleStore = () => {
    storeList()
      .then((res) => {
        const {code} = res;
        if (code === 0) {
          setStore(res.data);
        } else {
          message.error(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };


  const onMonthChange = (date, dateString) => {
    if (date && date._isAMomentObject) {
      const nowDate = date.startOf('month').format('YYYY-MM-DD');
      setTimer(nowDate);
      setTimerObj(date);
    }
  };
  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const {code, data} = res;
      code === 0 ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  const onChange = (checked) => {
    setChangeMoneyFlag(checked);
  };
  const outColumns = [
    {
      title: '导出时间',
      dataIndex: 'date',
      renderFormItem: () => {
        return (
          <DatePicker
            picker="month"
            allowClear={false}
            value={timerObj}
            onChange={onMonthChange}
          />
        );
      },
    },
    {
      title: '导出店铺',
      dataIndex: 'storeName',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            labelInValue
            placeholder="选择店铺"
            allowClear
            showSearch
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            onChange={(res) => {
              setStoreId(res.key);
            }}
          >
            {store && store.length > 0 ? store.map((item) => {
              return (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            }) : null}
          </Select>
        );
      },
    },
  ];

  useEffect(() => {
    handleStore();

  }, []);
  const detailColumns = [
    {
      title: '店铺名称',
      hideInSearch: true,
      dataIndex: 'storeName',
      valueType: 'storeName',
    },
    {
      title: '会员名',
      hideInSearch: true,
      dataIndex: 'memberName',
      key: 'memberName',
      width: 120,
    },
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      key: 'memberNumber',
    },
    {
      title: '转入金额',
      hideInSearch: true,
      dataIndex: 'preAmount',
      key: 'preAmount',
    },
    {
      title: '剩余金额',
      hideInSearch: true,
      dataIndex: 'currentAmount',
      key: 'currentAmount',
    },
    {
      title: '转入时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      key: 'createTime',
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.createTime).toLocaleString();
        } else {
          return '-';
        }
      },
      search: {
        transform: (value) => {
          return {
            startCreateTime: value[0],
            endCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '操作员',
      hideInSearch: true,
      dataIndex: 'operatorName',
      key: 'operatorName',

    },
  ];
  const preChangeColumns = [

    {
      title: '姓名',
      dataIndex: 'memberName',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <Input disabled value={changePreObj.memberName}/>;
      },
    },
    {
      title: '卡号',
      dataIndex: 'memberNumber',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <Input disabled value={changePreObj.memberNumber}/>;
      },
    },
    {
      title: '预存店铺',
      dataIndex: 'storeName',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <Input disabled value={changePreObj.storeName}/>;
      },
    },
    {
      title: '剩余金额',
      dataIndex: 'currentAmount',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <Input disabled value={changePreObj.currentAmount}/>;
      },
    },
    {
      title: '目标店铺',
      hideInTable: true,
      dataIndex: 'storeId',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '目标店铺为必填项',
          },
        ],
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择预存转移目标店铺"
            showSearch
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            allowClear
          >
            {store.map((item_, index) => {
              return (
                <Select.Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },

    {
      title: '调整金额',
      dataIndex: 'money',
      valueType: 'money',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '余额为必填项',
          },
        ],
      },
    },
    {
      title: '注:',
      dataIndex: 'tips',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <div>【调整金额】代表【剩余金额】转出数</div>;
      },
    },
  ];
  const columns = [
    {
      title: '店铺名称',
      hideInSearch: true,
      dataIndex: 'storeName',
      valueType: 'storeName',
    },
    {
      title: '店铺名称',
      hideInTable: true,
      dataIndex: 'storeId',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择消费店铺"
            showSearch
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            allowClear
          >
            {store.map((item_, index) => {
              return (
                <Select.Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '会员名',
      hideInSearch: true,
      dataIndex: 'memberName',
      key: 'memberName',
      width: 120,
    },
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      key: 'memberNumber',
    },
    {
      title: '预存金额',
      hideInSearch: true,
      dataIndex: 'preAmount',
      key: 'preAmount',
    },
    {
      title: '剩余金额',
      hideInSearch: true,
      dataIndex: 'currentAmount',
      key: 'currentAmount',
    },
    {
      title: '转移金额',
      hideInSearch: true,
      dataIndex: 'changeAmount',
      key: 'changeAmount',
    },
    {
      title: '余额消费金额',
      hideInSearch: true,
      dataIndex: 'balanceAmount',
      key: 'balanceAmount',
    },
    {
      title: '退款金额',
      hideInSearch: true,
      dataIndex: 'withdrawAmount',
      key: 'withdrawAmount',
    },
    {
      title: '累计积分',
      hideInSearch: true,
      dataIndex: 'totalIntegral',
      key: 'totalIntegral',
    },
    {
      title: '预存状态',
      hideInSearch: true,
      dataIndex: 'overroll',
      key: 'overroll',
      valueEnum: {
        true: {
          text: '消费完',
          status: 'Default',
        },
        false: {
          text: '预存中',
          status: 'Processing',
        },
      },
    },
    {
      title: '撤销状态',
      hideInSearch: true,
      dataIndex: 'deleted',
      key: 'deleted',
      valueEnum: {
        true: {
          text: '已退款',
          status: 'Default',
        },
        false: {
          text: '未退款',
          status: 'Processing',
        },
      },
    },
    {
      title: '预存时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      key: 'createTime',
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.createTime).toLocaleString();
        } else {
          return '-';
        }
      },
      search: {
        transform: (value) => {
          return {
            startCreateTime: value[0],
            endCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {

        return (
          <>
            <Access accessKey={"@seeOrderDetailByStoreRechargeCount"}>
              <a
                onClick={() => {
                  if (record.orderId && record.orderId!=0){
                    handlePay(record.orderId);
                    setOrder(true);
                  }else{
                    message.warn('初始数据没有关联订单!');
                  }
                }}
              >
                查看订单
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@updateStoreRecharge"}>
              <a
                onClick={() => {
                  setChangePreObj(record);
                  handlePreChangeVisibleVisible(true);
                }}
              >
                调整预存
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@seeUpdateStoreRechargeDetail"}>
              <a
                onClick={() => {
                  setChangePreObj(record);
                  handlePreDetailVisible(true);
                }}
              >
                调整明细
              </a>
            </Access>

          </>
        );
      }
    },
    {
      title: '查询转移金额',
      hideInTable: true,
      dataIndex: 'changeMoney',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <div>
            <Switch onChange={onChange} />
          </div>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <CreateForm
        width={1000}
        title={'预存调整明细'}
        onCancel={() => handlePreDetailVisible(false)}
        modalVisible={preDetailVisible}
      >
        <ProTable
          rowKey="detailId"
          scroll={{x: 900}}
          bordered
          footer={null}
          toolBarRender={false}
          search={false}
          request={(params, sorter, filter) => {
            return getChangePrePage({...params, sorter, filter},changePreObj.id);
          }}
          postData={(params) => {
            const {list, total} = params;
            setDetailCount(total);
            return list || [];
          }}
          pagination={{
            defaultPageSize: 30,
            showSizeChanger: true,
            showTitle: false,
            total: detailCount,
            showTotal: (total) => `共${total}条`,
          }}
          columns={detailColumns}
        />
      </CreateForm>
      <CreateForm
        width={800}
        title={'预存调整'}
        onCancel={() => {
          handlePreChangeVisibleVisible(false);
        }}
        modalVisible={preChangeVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            const hide = message.loading('正在添加');
            const params = {
              id:changePreObj.id,
              storeId:value.storeId,
              money:value.money
            };
            try {
              await changePre(params);
              hide();
              message.success('调整成功');
              handlePreChangeVisibleVisible(false);
              actionRef.current.reload();
              return true;
            } catch (error) {
              hide();
              message.error('添加失败请重试！');
              handlePreChangeVisibleVisible(false);
              return false;
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: '',
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={preChangeColumns}
        />
      </CreateForm>

      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => handleOutModal(false)}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            let list = {
              type: 'pre',
              storeId: storeId ? storeId : '',
              date: timer,
            };
            exportPreCount(list)
              .then((res) => {
                if (res) {
                  if (res.size>0){
                    saveFileAs(res, '店铺预存统计');
                  }else {
                    message.info('暂无数据');
                  }
                } else {
                  message.info(res.message);
                }
              })
              .catch((err) => {
                message.error(err);
              });
          }}
          rowKey="id"
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        scroll={{x: 1200}}
        bordered
        footer={null}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          return (
            <Access accessKey={"@exportStoreRechargeCount"}>
              <div>
                <Button
                  onClick={() => handleOutModal(true)}
                >
                  导出店铺预存统计
                </Button>
              </div>
            </Access>
          );
        }}
        request={(params, sorter, filter) => {
          params.changeMoneyFlag = changeMoneyFlag;
          return getPreStore({...params, sorter, filter});
        }}
        postData={(params) => {
          const {list, total} = params;
          setCount(total);
          return list || [];
        }}
        onReset={(params) => {
          setTimeout(() => {
            actionRef.current.reload();
          }, 0);
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      <CreateForm width={1300} onCancel={() => setOrder(false)} modalVisible={order} footer={null}>
        <OrderCommon
          payOrderValues={payOrderValues}
          refund={null}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default StoreRecharge;
